import { Injectable } from '@angular/core';

import { Http } from '@angular/http';
import { Service } from '../../server/server';

@Injectable()
export class EffectService {

    //config: Config;
    private baseUrl: string = '';

    constructor(private http: Http, private context: Service) {
        this.baseUrl = context.zsurl;
    }


    getParentInfos(data: any): Promise<Array<any>> {
        let url = this.context.baseUrl+'user/functions/getParentInfos';
        return this.http
            .get(url)
            .toPromise()
            .then(res => {
                let r = res.json();
                if (r.result_code !== '0000') {
                    throw new Error(r.message);
                } else {
                    //return Array<any>(r.result);
                    return this.processTreeData(r.result);
                }
            });
    }

    private processTreeData(list: Array<any>): Array<any> {
        return this.getTreeChildren(list, "0");
    }

    private getTreeChildren(list: Array<any>, parentId: string): Array<any> {
        let idKey: string = 'functionId';
        let labelKey: string = 'functionName';
        let result: Array<any> = [];
        for (let item of list) {
            if (item.parentId === parentId) {
                this.fillCSTreeNode(item, item[idKey], item[labelKey]);
                let children = this.getTreeChildren(list, item[idKey]);
                if (children && children.length > 0) {
                    item.children = children;
                    item.leaf = false;
                } else {
                    item.leaf = true;
                }
                result.push(item);
            }
        }
        return result;
    }

    private fillCSTreeNode(node: any, data: string, label: string): void {
        node.data = data;
        node.label = label;
        node.expandedIcon = 'fa-minus-square-o';
        node.collapsedIcon = 'fa-plus-square-o';
        node.expanded = false;
        node.leaf = false;
        //console.log(node)
        //node.icon = 'fa-dot-circle-o';
    }


}

